package cn.windfly.don;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import cn.windfly.don.listener.DependsOnNameListener;
import cn.windfly.util.DateUtil;
import cn.windfly.util.FileUtil;
import cn.windfly.util.LogUtil;
import cn.windfly.util.StringUtil;

/**
 * 与DON框架耦合的一些工具方法
 * 
 * @author DingFengHua
 * 
 */
public class DonUtil {

	public static void createUploadDirWithDeafultRoot(String dirName) {
		FileUtil.createUploadDir(DependsOnNameListener.BasePath, "resources/upload/" + dirName, null);
	}

	public static void createUploadDir(String relativePath) {
		FileUtil.createUploadDir(DependsOnNameListener.BasePath, relativePath, null);
	}

	public static void createUploadDirWithDeafultRootAndDateName(String relativePath) {
		FileUtil.createUploadDir(DependsOnNameListener.BasePath, relativePath, "yyyyMMdd");
	}

	public static void createUploadDirDefaultRoot() {
		FileUtil.createUploadDir(DependsOnNameListener.BasePath, "resources/upload", "yyyyMM");
	}

	public static String copyUploadFileToDefaultDirs(File file) {
		String relatepath = "/resources/upload/" + DateUtil.formatDate(new Date(), "yyyyMM");
		String name = file.getName();
		String hash = Math.abs((name+System.currentTimeMillis()+"").hashCode())+"";
		if (name.contains(".")) {
			name = name.substring(name.lastIndexOf("."));
		}
		name = hash + name;
		String newFilename = DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") + "-"
				+ StringUtil.randomNumberValidCode(4) + name;
		String dirStr = DependsOnNameListener.BasePath + relatepath;
		File dir = new File(dirStr);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		file.renameTo(new File(dirStr + "/" + newFilename));
		String filepre = DonConfig.getString("don.upload.origin","..");
		return filepre + relatepath + "/" + newFilename;
	}

	public static void removeUploadFile(String imgSrc) {
		String file = DependsOnNameListener.BasePath + imgSrc.replaceFirst("[.][.][/]", "");
		File f = new File(file);
		f.delete();
	}

	public static void downLoadFile(String fileName, byte[] fileBytes, HttpServletResponse response) {
		try {
			fileName = new String(fileName.getBytes("gb2312"),"ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream;charset=utf-8");
			response.setHeader("Content-disposition", "attachment;filename= " + fileName);
			response.getOutputStream().write(fileBytes);
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (IOException e) {
			LogUtil.error(e);
		}
	}
}
